package com.hqd.ch03.v26.spel.express;

import com.hqd.ch03.v26.spel.BeanExpressionResolver;
import com.hqd.ch03.v26.spel.Expression;
import com.hqd.ch03.v26.spel.ExpressionParser;
import com.hqd.ch03.v26.spel.ParserContext;
import com.hqd.ch03.v26.spel.accessor.BeanExpressionContextAccessor;
import com.hqd.ch03.v26.spel.context.StandardEvaluationContext;
import com.hqd.ch03.v26.spel.parse.InternalSpelExpressionParser;
import com.hqd.ch03.v26.spel.parse.TemplateParserContext;
import org.apache.commons.lang3.StringUtils;

public class StandardBeanExpressionResolver implements BeanExpressionResolver {
    private final ParserContext beanExpressionParserContext = new TemplateParserContext();
    private ExpressionParser expressionParser;

    public StandardBeanExpressionResolver() {
        this.expressionParser = new InternalSpelExpressionParser();
    }

    @Override
    public Object evaluate(String value, BeanExpressionContext beanExpressionContext) {
        if (StringUtils.isBlank(value)) {
            return value;
        }
        Expression expr = this.expressionParser.parseExpression(value, this.beanExpressionParserContext);
        StandardEvaluationContext sec = new StandardEvaluationContext(beanExpressionContext);
        sec.addPropertyAccessor(new BeanExpressionContextAccessor());
        return expr.getValue(sec);
    }
}
